<template>
  <div class="cg-add-edit-modal">
    <a-modal
      v-if="visible"
      width="800px"
      :title="modalTitle"
      :visible="visible"
      :confirm-loading="confirmLoading"
      :destroy-on-close="true"
      @ok="handleSubmitClick"
      @cancel="resetFormModalData"
    >
      <a-form-model
        ref="formRef"
        :model="form"
        :rules="formRules"
        layout="vertical"
      >
        <a-row :gutter="24">
          <a-col
            v-for="item in this.addEditFormDataCopy"
            :key="typeof item.field === 'string' ? item.field : item.field[0]"
            :span="item.col"
          >
            <a-form-model-item
              v-if="item.type === 'input'"
              :label="item.label"
              :prop="item.field"
            >
              <a-input
                v-model="form[item.field]"
                :placeholder="item.placeholder"
              />
            </a-form-model-item>
            <a-form-model-item
              v-else-if="item.type === 'select'"
              :label="item.label"
              :prop="item.field"
            >
              <a-select
                :showSearch="true"
                :allowClear="true"
                :placeholder="item.placeholder"
                :filterOption="filterSelectOption"
                v-model="form[item.field]"
              >
                <a-select-option
                  v-for="select in item.option"
                  :value="select.value"
                  :key="select.value"
                >
                  {{ select.text }}
                </a-select-option>
              </a-select>
            </a-form-model-item>
            <a-form-model-item
              v-else-if="item.type === 'date'"
              :label="item.label"
              :prop="item.field"
            >
              <a-date-picker
                style="width: 100%"
                :show-time="false"
                :placeholder="item.placeholder"
                :default-value="item.defaultValue ? moment(item.defaultValue, 'YYYY-MM-DD') : null"
                @change="(date) => { handleDateChange(date, item.field, 'YYYY-MM-DD') }"
              />
            </a-form-model-item>
            <a-form-model-item
              v-else-if="item.type === 'datetime'"
              :label="item.label"
              :prop="item.field"
            >
              <a-date-picker
                style="width: 100%"
                :show-time="true"
                :placeholder="item.placeholder"
                :default-value="item.defaultValue ? moment(item.defaultValue, 'YYYY-MM-DD hh:mm:ss') : null"
                @change="(date) => { handleDateChange(date, item.field, 'YYYY-MM-DD hh:mm:ss') }"
              />
            </a-form-model-item>
            <a-form-model-item
              v-else-if="item.type === 'rang-date'"
              :label="item.label"
              :prop="item.field[0]"
            >
              <a-range-picker
                style="width: 100%"
                :show-time="false"
                :placeholder="item.placeholder"
                :default-value="[
                item.defaultValue ? moment(item.defaultValue[0], 'YYYY-MM-DD') : null,
                item.defaultValue ? moment(item.defaultValue[1], 'YYYY-MM-DD') : null
              ]"
                @change="(date) => { handleRangPickerChange(date, item.field, 'YYYY-MM-DD') }"
              />
            </a-form-model-item>
            <a-form-model-item
              v-else-if="item.type === 'rang-datetime'"
              :label="item.label"
              :prop="item.field[0]"
            >
              <a-range-picker
                style="width: 100%"
                :show-time="true"
                :placeholder="item.placeholder"
                :default-value="[
                item.defaultValue ? moment(item.defaultValue[0], 'YYYY-MM-DD hh:mm:ss') : null,
                item.defaultValue ? moment(item.defaultValue[1], 'YYYY-MM-DD hh:mm:ss') : null
              ]"
                @change="(date) => { handleRangPickerChange(date, item.field, 'YYYY-MM-DD hh:mm:ss') }"
              />
            </a-form-model-item>
          </a-col>
        </a-row>
      </a-form-model>
    </a-modal>
  </div>
</template>

<script>
import emitter from '@/utils/emitter';
import Events from '@/utils/event';
import { cloneDeep, forEach, get, map } from 'lodash-es';
import moment from 'moment';
import axiosInstance from '@/utils/axiosInstance';

export default {
  name: 'CgAddEditModal',
  props: {
    addEditFormData: {
      type: Array,
      default: () => ([])
    },
    getData: {
      type: Function
    },
    createData: {
      type: Function
    },
    updateData: {
      type: Function
    }
  },
  data () {
    return {
      addEditFormDataCopy: [],
      formRules: {},
      modalTitle: '',
      visible: false,
      confirmLoading: false,
      form: {}
    };
  },
  methods: {
    moment,
    // 初始化 form model item
    initFormItems () {
      this.addEditFormDataCopy = cloneDeep(this.addEditFormData);
      forEach(this.addEditFormDataCopy, item => {
        const type = item.type;
        // 设置 form item
        this.setFormItem(item, type);
        // 设置 form rule
        this.setRuleByType(item, type);
      });
    },
    setFormItem (data, type) {
      const { field, optionConf } = data;
      if (type === 'input') {
        this.$set(this.form, field, '');
      } else if (type === 'select') {
        this.$set(this.form, field, undefined);
        if (optionConf) {
          axiosInstance.request({
            url: optionConf.url,
            method: optionConf.method
          }).then(res => {
            const list = get(res, 'result');
            data.option = map(list, item => {
              return {
                text: item[optionConf.textKey],
                value: item[optionConf.valueKey]
              };
            });
            console.log(data);
          });
        }
      } else if (type === 'date' || type === 'datetime') {
        this.$set(this.form, field, '');
      } else if (type === 'rang-date' || type === 'rang-datetime') {
        this.$set(this.form, field[0], '');
        this.$set(this.form, field[1], '');
      }
    },
    setRuleByType ({ rule, field }, type) {
      if (rule) {
        if (type === 'rang-date' || type === 'rang-datetime') {
          this.$set(this.formRules, field[0], rule);
        } else {
          this.$set(this.formRules, field, rule);
        }
      }
    },
    // 设置 date-picker 的 default value
    setDatePickersDefaultValue () {
      forEach(this.addEditFormDataCopy, item => {
        const type = item.type;
        if (type === 'date' || type === 'datetime') {
          item.defaultValue = this.form[item.field];
        } else if (type === 'rang-date' || type === 'rang-datetime') {
          item.defaultValue = [this.form[item.field[0]], this.form[item.field[1]]];
        }
      });
    },
    // 提交
    handleSubmitClick () {
      this.confirmLoading = true;
      this.$refs.formRef.validate(valid => {
        if (valid) {
          if (this.form.id) {
            this.updateDataAction();
          } else {
            this.createDataAction();
          }
        } else {
          this.confirmLoading = false;
          return false;
        }
      });
    },
    // 取消
    resetFormModalData (e) {
      this.form = {};
      this.addEditFormDataCopy = [];
      this.visible = false;
    },
    updateDataAction () {
      this.updateData(this.form).then(res => {
        this.$message.success(res.msg);
        this.resetFormModalData();
        emitter.emit(Events.REFRESH_TABLE, false);
      }).catch(e => {
        this.$message.error(e.msg);
      }).finally(() => {
        this.confirmLoading = false;
      });
    },
    createDataAction () {
      this.createData(this.form).then(res => {
        this.$message.success(res.msg);
        this.resetFormModalData();
        emitter.emit(Events.REFRESH_TABLE, true);
      }).catch(e => {
        this.$message.error(e.msg);
      }).finally(() => {
        this.confirmLoading = false;
      });
    },
    // 显示 modal
    showModal ({ type, id }) {
      this.initFormItems();
      if (type === 'EDIT') {
        this.modalTitle = '编辑';
        this.getData(id).then(res => {
          console.log(res);
          this.form = res.result;
          this.setDatePickersDefaultValue();
          this.visible = true;
        });
      } else if (type === 'ADD') {
        this.modalTitle = '新增';
        this.visible = true;
      }
    },
    // 用于 select 搜索
    filterSelectOption (value, option) {
      return option.componentOptions.children[0].text.indexOf(value) >= 0;
    },
    // date 发生改变
    handleDateChange (date, field, format) {
      if (date) {
        this.form[field] = moment(date._d).format(format);
      } else {
        this.form[field] = '';
      }
    },
    // rang 发生改变
    handleRangPickerChange (date, fields, format) {
      if (date && date.length) {
        this.form[fields[0]] = moment(date[0]._d).format(format);
        this.form[fields[1]] = moment(date[1]._d).format(format);
      } else {
        this.form[fields[0]] = '';
        this.form[fields[1]] = '';
      }
    }
  },
  mounted () {
    emitter.on(Events.SHOW_ADD_EDIT_MODAL, this.showModal);
  },
  beforeDestroy () {
    emitter.off(Events.SHOW_ADD_EDIT_MODAL);
  }
};
</script>

<style scoped>

</style>
